<?
//----------------------------------------------------------------------------------
function get_master_connect(){
	global  $session_db_host, $session_db_user, $session_db_pass;
	if (!$dbh = @mysql_connect($session_db_host, $session_db_user, $session_db_pass))
		return 0;
	return $dbh;
}
//----------------------------------------------------------------------------------
function exit_now(){
	global  $dbh;
	if ($dbh)
		mysql_close($dbh);
	exit;
}
//----------------------------------------------------------------------------------
function kill_old_sessions(){
	global $session_db_name, $dbh,$sessionexp,$userName;
	if($userName){
		$lenght = strlen($userName);
		$patch = " and sess_data like '%s:8:\"userName\";s:$lenght:\"$userName\"%'";
	}
	$SQL = "delete from sessions where tstamp  < date_add(now(), interval - $sessionexp minute) $patch";
	if (!($result1 = @mysql_db_query($session_db_name, $SQL, $dbh)))
		return 0;
	else
		return 1;
}
function kill_session($sid){
	$SQL="delete from sessions where id='sid'";
	if (!($result = @mysql_db_query($session_db_name, $SQL, $dbh)))	return 0;
	return 1;
}
//----------------------------------------------------------------------------------
function is_blocked($username){
	global $session_db_name, $dbh;
	$SQL = "select state from resellers where resellername='$username'";
	if (($result = @mysql_db_query($session_db_name, $SQL, $dbh)) && ($row=mysql_fetch_array($result)) && ($row[state]=="B") ) return 1;
	return 0;
}
//----------------------------------------------------------------------------------
function transaction($SQL,$type='0'){
	global $session_db_name, $dbh;

	if(!$dbh) $dbh  = get_master_connect();

	if (!($result = mysql_db_query($session_db_name,"BEGIN", $dbh))) return 0;
	foreach($SQL as $q){
		if($q){
			//echo "$q <br>";
			if (!($result = mysql_db_query($session_db_name, $q, $dbh))){
				//echo mysql_error($result);
				$result = mysql_db_query($session_db_name,"ROLLBACK", $dbh);
				return 0;
			}
			if(!$type){
				if(mysql_affected_rows($dbh) == 0){
					$result = mysql_db_query($session_db_name,"ROLLBACK", $dbh);
					return 0;
				}
			}
		}
	}
	if (!($result = mysql_db_query($session_db_name,"COMMIT", $dbh))) return 0;

	return 1;
}
//---------------------------------------------------------------
function encode_params($params){
        $chars = array(
                "=" => "_",
                "+" => "-"
                );
        return strtr(strrev(base64_encode(@gzcompress(serialize($params)))),$chars);
}
//---------------------------------------------------------------
function decode_params(){
        $buffer = explode("|||",$_SERVER['QUERY_STRING']);
        $buffer = $buffer[0];
        $chars = array(
                "_" => "=",
                "-" => "+"
                );
        return unserialize(@gzuncompress(base64_decode(strrev(strtr($buffer,$chars)))));
}
//---------------------------------------------------------------------------------
function include_template($file){
	global $webDIR,$baseURL,$sid,$params,$userName,$errorMsg,$statusMsg;
	include("main.html");
}
//---------------------------------------------------------------------------------
function validate($string) {
        return preg_match('/^[^\000-\037\'"`\']+$/', $string)?$string:'';
}
//---------------------------------------------------------------------------------
function get_countries($country=''){
	global $session_db_name, $dbh;
	$SQL="select name,iso2 from countries order by name asc";
	if (!($result = mysql_db_query($session_db_name,$SQL, $dbh))) return 0;
	while($row=mysql_fetch_array($result)){
		if($country=="$row[iso2]") $res.="<option value='$row[iso2]' selected >$row[name]</option>";
		else $res.="<option value='$row[iso2]'>$row[name]</option>";
	}
	return $res;
}
//---------------------------------------------------------------------------------
function generate_code($arr,$name="HTTP_POST_VARS"){
	if(is_array($arr)){
		while(list($k,$v)=each($arr)){
			$init.="$k=\$".$name."[".$k."]; <br>\n";
			$validate.="if(!validate($k)){
				\$errorCode=1;
				\$errorMsg=\" invalid  $k \";
				\$fileTemplate='openNormal.html';
				include(main.html);
				exit();
				}
				<br>\n";
			//$validate.="\$".$k."=validate(\$".$k.");<br>";
			$params[]="\$info[$k]";
		}
		$function_calling="if(!function_calling(".implode(",",$params).")";
		$error.="\n<br>	\$error_url=\"\";
				<br><br>\n";
		reset($arr);
	}
	$res="$init<br><br>$validate$function_calling";
	return $res;
}

//----------------------------------------------------------------------------------
function reseller_exists($reseller){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT reseller FROM resellers WHERE reseller='$reseller'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function check_user_pass($user,$password){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT reseller FROM resellers WHERE reseller='$user' and password='$password'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else return 1;

}
//-----------------------------------------------------------------------------
function get_reseller_id($reseller){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT id FROM resellers WHERE reseller='$reseller'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else {
		$row = @mysql_fetch_array($result);		
	}
	return $row[id];

}
//-----------------------------------------------------------------------------
function change_details($id,$details){
	global $session_db_name, $dbh,$sid;
	$SQL = "UPDATE resellers SET

			firstname='$details[firstname]',
			lastname='$details[lastname]',
			email='$details[email]',
			phone='$details[phone]',
			address1='$details[address1]',
			address2='$details[address2]',
			city='$details[city]',
			state='$details[state]',
			zip='$details[zip]',
			country='$details[country]'

			WHERE id = '$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function change_bank_details($id,$details){
	global $session_db_name, $dbh,$sid;
	$SQL = "UPDATE resellers SET

			swift_code='$details[swift_code]',
			bank_name='$details[bank_name]',
			bank_address='$details[bank_address]',
			account_number='$details[account_number]',
			routing_number='$details[routing_number]',
			account_holder='$details[account_holder]',
			payment_method='$details[payment_method]',
			current_release_level='$details[current_release_level]'

			WHERE id = '$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function change_password($id,$password){
	global $session_db_name, $dbh,$sid;
	$SQL = "UPDATE resellers SET password='$password' WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function change_interface_settings($id,$settings){
	global $session_db_name, $dbh,$sid;
	if(reseller_has_plan($id,$settings[plan],"interface")){
		$SQL = "UPDATE interface SET
				display='$settings[display]',
				domain='$settings[domain]'
				WHERE id='$id' and plan='$settings[plan]'";
	}
	else{
		$SQL = "INSERT INTO interface SET
				id='$id',
				plan='$settings[plan]',
				display='$settings[display]',
				domain='$settings[domain]'";
	}
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;
}

//-----------------------------------------------------------------------------
function reseller_has_plan($id,$plan,$type='reseller_plans'){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT plan FROM $type WHERE id='$id' and plan='$plan'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh))  || !@mysql_num_rows($result) )
			return 0;
	else return 1;
}
//-----------------------------------------------------------------------------
function change_plan_settings($id,$settings){
	global $session_db_name, $dbh,$sid;

	if(reseller_has_plan($id,$settings[plan])){
		$SQL = "UPDATE reseller_plans SET
			 setup_fee='$settings[setup_fee]',
			domain_price=$settings[domain_price],
			plan_price=$settings[plan_price]
			WHERE id='$id' and plan='$settings[plan]'";
	}
	else{
		$SQL = "INSERT INTO  reseller_plans SET
			 id='$id',
			plan='$settings[plan]',
			setup_fee='$settings[setup_fee]',
			domain_price=$settings[domain_price],
			plan_price=$settings[plan_price]";
	}
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	else return 1;

}
//-----------------------------------------------------------------------------
function list_reseller_plans($id,$type='table'){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
		rp.setup_fee,
		rp.domain_price,
		rp.plan_price,
		p.plan,
		p.description,
		p.setup_fee_max,
		p.plan_min_price,
		p.plan_real_price,
		p.plan_max_price,
		p.domain_min_price,
		p.domain_real_price,
		p.domain_max_price
		FROM  plans p
		LEFT JOIN reseller_plans rp on p.plan=rp.plan and  rp.id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "select":
				$list .= "";
			break;
			case "checkbox":
				$list .="";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;
}
//-----------------------------------------------------------------------------
function list_details($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				id,
				reseller,
				password,
				firstname,
				lastname,
				email,
				phone,
				address1,
				address2,
				city,
				state,
				zip,
				country
			FROM resellers
			WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;

}
//-----------------------------------------------------------------------------
function list_bank_details($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				swift_code,
				bank_name,
				bank_address,
				account_number,
				routing_number,
				account_holder,
				payment_method,
				current_release_level
			FROM resellers
			WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;

}
//-----------------------------------------------------------------------------
function list_payment_history($id,$type,$details){ // ??
        global $session_db_name, $dbh,$sid;
        switch($type){
                case "period":
			$SQL = "select date_format(date,'%Y-%m') as sdate,PERIOD_DIFF(date_format(now(),'%Y%m'),date_format(date,'%Y%m')) as periods from resellers where id='$id'";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        $row = @mysql_fetch_array($result);
                        $signup_date = $row[sdate];
                        $periods_count = $row[periods];
                        for($i=0;$i<=$periods_count;$i++){
                        	$bdate = explode("-",$row[sdate]);
                        	$bdate = date("Y-m",mktime(0,0,0,$bdate[1]+$i,1,$bdate[0]));
                        	$hash[$bdate]="";
                        }
                        $SQL = "select
                       		date_format(date,'%Y-%m') as date,
                                date_format(payment_date,'%Y-%m-%d') as payment_date,
                                (sum(price)-sum(real_price)) as sum
                                from sales
                                where
                                payed='true' and
                                state!='refund' and
                                id='$id'
                                group by date_format(date,'%Y-%m')";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        while ($row = @mysql_fetch_array($result)) {
                        		$hash[$row[date]][sum] = $row[sum];
                        		$hash[$row[date]][pdt] = $row[payment_date];
                        }
			while(list($date,$h) = each($hash)){
				if(!$h[sum]) $h[sum] = 0;
				if(!$h[pdt]) $h[pdt] = "&nbsp;";
                                $list .= "<tr>
                                                        <td>".$date."</td>
                                                        <td>\$".$h[sum]."</td>
                                                        <td>".$h[pdt]."</td>
                                                </tr>";
                        }
                        return $list;
                break;
                case "unpayed_period":
                        $SQL = "select
                       		date_format(date,'%Y-%m') as date,
                                (sum(price)-sum(real_price)) as sum
                                from sales
                                where
                                payed='false' and
                                state!='refund' and
                                id='$id'
                                group by date_format(date,'%Y-%m')";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        while ($row = @mysql_fetch_array($result)) {
                        		$hash[$row[date]][date] = $row[date];
                        		$hash[$row[date]][sum] = $row[sum];
                        }
                        if(is_array($hash)){
				foreach($hash as $h){
                                	$list .= "<tr>
                                                        <td>".$h[date]."</td>
                                                        <td>\$".$h[sum]."</td>
                                                        <td>Unpayed</td>
                                                </tr>";
	                        }
			}
                        return $list;
		break;
                case "details_normal":
                        if(is_array($details)){
                                $SQL = "SELECT
						type,
						count(type) as count,
						sum(price) as price,
						sum(real_price) as real_price,
						(sum(price)-sum(real_price)) as profit
						FROM sales
						WHERE
						id='$id' and
						state!='refund' and
						date >= '$details[start]' and
						date <= '$details[end]'
						group by type";
                                if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                                return 0;
                                while ($row = @mysql_fetch_array($result)) {
                                	$list[$row[type]] = $row;
                                }
                                return $list;
                        }
                        return 0;
                break;
                case "details_refund":
                        if(is_array($details)){
                                $SQL = "SELECT
                                                type,
                                                count(type) as count,
                                                sum(price) as price,
                                                sum(real_price) as real_price,
                                                (sum(price)-sum(real_price)) as profit
                                                FROM sales
                                                WHERE
                                                id='$id' and
                                                state='refund' and
                                                date >= '$details[start]' and
                                                date <= '$details[end]'
                                                group by type";
                                if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                                return 0;
                                while ($row = @mysql_fetch_array($result)) {
                                        $list[$row[type]] = $row;
                                }
                                return $list;
                        }
                        return 0;
                break;
        }

}
//-----------------------------------------------------------------------------
function get_signup_date($id){
        global $session_db_name, $dbh,$sid;
        		$SQL = "select date_format(date,'%Y-%m-%d') as sdate from resellers  where id='$id'";
                        if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
                                        return 0;
                        $row = @mysql_fetch_array($result);
                        $signup_date = $row[sdate];
         if($signup_date) return $signup_date;
         else return '2000-01-01';
}
//-----------------------------------------------------------------------------
function list_interface_settings($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				id,
				plan,
				display,
				domain
			FROM interface
			WHERE id='$id'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[$row[plan]] = $row;
			break;
		}
	}
	return $list;
}
//-----------------------------------------------------------------------------
function list_refunds($id,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				id
				client
				type
				price
				real_price
				date
				payed
				payment_date
				state
				log_id
			FROM sales
			WHERE id='$id' and state='refund'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
		}
	}
	return $list;
}
//-----------------------------------------------------------------------------
function list_plan_details($plan,$type){
	global $session_db_name, $dbh,$sid;
	$SQL = "SELECT
				plan,
				description,
				alias,
				setup_fee_max,
				plan_min_price,
				plan_real_price,
				plan_max_price,
				domain_min_price,
				domain_real_price,
				domain_max_price
			FROM plans
			WHERE plan='$plan'";
	if ( !($result = @mysql_db_query($session_db_name, $SQL, $dbh)))
			return 0;
	while ($row = @mysql_fetch_array($result)) {
		switch($type){
			case "table":
				$list .= "";
			break;
			case "array":
				$list[] = $row;
			break;
		}
	}
	return $list;

}
//-----------------------------------------------------------------------------

?>
